package com.gs.SynAntiWandering.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.gs.SynAntiWandering.R;
import com.gs.SynAntiWandering.activity.base.BaseActivity;
import com.gs.SynAntiWandering.apiresult.ApiResultData;
import com.gs.SynAntiWandering.apiresult.LoginData;
import com.gs.SynAntiWandering.constant.AllConstants;
import com.gs.SynAntiWandering.control.EditTextDRClick;
import com.gs.SynAntiWandering.db.dto.UserDto;
import com.gs.SynAntiWandering.presenter.LoginPresenter;
import com.gs.SynAntiWandering.util.CaptchaUtil;
import com.gs.SynAntiWandering.util.NetworkUtil;
import com.gs.SynAntiWandering.util.PermissionUtil;
import com.gs.SynAntiWandering.util.SPUtil;
import com.gs.SynAntiWandering.util.ToastUtil;
import com.gs.SynAntiWandering.util.WindowUtil;
import com.gs.SynAntiWandering.view.ILoginView;

public class LoginActivity extends BaseActivity<ILoginView, LoginPresenter> implements ILoginView {

    private EditText etName, etCode;
    private EditTextDRClick etPassword;
    private TextView tvCode, tvBack;
    private String code;
    private Button btnSignIn;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        WindowUtil.setWindowDecorView(this);
        OnClickListener onClickListener = new OnClickListener();
//        用户名
        etName = fd(R.id.et_name);
        etName.setText(SPUtil.getInstance().getString(AllConstants.USER));
//        密码
        etPassword = fd(R.id.et_password);
//        验证码显示
        tvCode = fd(R.id.tv_code);
        showCode();
//        刷新验证码
        fd(R.id.iv_refresh).setOnClickListener(onClickListener);
//        输入验证码
        etCode = fd(R.id.et_member_name);
//        登录
        btnSignIn = fd(R.id.btn_signin);
        btnSignIn.setOnClickListener(onClickListener);
//        返回
        tvBack = fd(R.id.tv_back);
        tvBack.setOnClickListener(onClickListener);
        tvBack.setVisibility(getIntent().getIntExtra(AllConstants.WHAT, 0) == 0 ? View.GONE : View.VISIBLE);
//        忘记密码
        fd(R.id.tv_forgotpw).setOnClickListener(onClickListener);
        PermissionUtil.addIgnoringBatteryOptimizations(this);
    }

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    @Override
    public void per() {

    }

    @Override
    public String getUserName() {
        return etName.getText().toString();
    }

    @Override
    public String getPassword() {
        return etPassword.getText().toString();
    }

    @Override
    public void onLoginSuccess(ApiResultData<LoginData> apiResultData) {
        btnSignIn.setEnabled(true);
        if (apiResultData.getStatus() != 2000) {
            ToastUtil.showToast(apiResultData.getMessage());
            return;
        }
        UserDto userInfo = apiResultData.getData().getUserInfo();
        SPUtil.getInstance().putString(AllConstants.USER, userInfo.getUserName());
        SPUtil.getInstance().putString(AllConstants.ID, userInfo.getId());
        SPUtil.getInstance().putString(AllConstants.TOKEN,
                apiResultData.getData().getToken() == null ? "" : apiResultData.getData().getToken());
        SPUtil.getInstance().putString(AllConstants.REFRESH_TOKEN,
                apiResultData.getData().getRefreshToken() == null ? "" : apiResultData.getData().getRefreshToken());
        if (userInfo.getSite() != null) {
            SPUtil.getInstance().putString(AllConstants.SITE_ID,
                    userInfo.getSite().getId() == null ?
                            "" : userInfo.getSite().getId());
            SPUtil.getInstance().putString(AllConstants.SITE_NAME,
                    userInfo.getSite().getName() == null ? "" :
                            userInfo.getSite().getName());
        }
        try {
            SPUtil.getInstance().putInt(AllConstants.LANGUAGE,
                    userInfo.getLang() == null ? 1 :
                            Integer.parseInt(userInfo.getLang().getId()));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        WindowUtil.hideSoftInput(getCurrentFocus());
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
//        intent.putExtra(AllConstants.WHAT,1000);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public void onLoginFail(Exception e) {
        btnSignIn.setEnabled(true);
        ToastUtil.showToast( R.string.network_error);
    }

    class OnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            int id = v.getId();// 刷新验证码
            if (id == R.id.iv_refresh) {
                showCode();
                // 登录
            } else if (id == R.id.btn_signin) {
                signIn(v);
                // 忘记密码
            } else if (id == R.id.tv_forgotpw) {
                startActivity(new Intent(LoginActivity.this, ForgotPwActivity.class));
            } else if (id == R.id.tv_back) {
                finish();
            }
        }
    }

    private void signIn(View v) {
        if (TextUtils.isEmpty(getUserName())) {
            ToastUtil.showToast(R.string.username_hint);
            return;
        }
        if (TextUtils.isEmpty(getPassword())) {
            ToastUtil.showToast(R.string.pw_hint);
            return;
        }
        if (etCode.getText().toString().equalsIgnoreCase(code)) {
            if (NetworkUtil.getInstance().isConnected()) {
                v.setEnabled(false);
                mPresenter.login();
            } else {
                ToastUtil.showToast(R.string.network_error);
            }
        } else {
            ToastUtil.showToast(R.string.code_fail);
        }
    }

    /**
     * 生成验证码并展示
     */
    private void showCode() {
        code = CaptchaUtil.getInstance().getRandomCode(4);
        tvCode.setText(code);
    }
}